package com.wzh.yebServe.config;

import com.wzh.yebServe.config.security.MyUserDetailService;
import com.wzh.yebServe.utils.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @Author wzh
 * @create 2022/11/22 16:27
 * @Description:
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig  implements WebSocketMessageBrokerConfigurer {
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;



    @Autowired
    private MyUserDetailService myUserDetailService;
    /**
     * 添加这个Endpoints这样在网页可以通过webSocket连接上服务
     * 也就是我们配置websocket的服务地址，并且可以指定是否使用socketJS
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        /**
         * 将ws/ep路径注册为stomp的端点，用户连接了这个端点就可以进行webSocket通讯，支持socketJs
         * setAllowedOrigins("*") 允许跨域
         * withSockJS();支持SockJS访问
         */
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();

    }


    /**
     * 输入通达参数配置
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
//                判断是不是链接
                StompHeaderAccessor accessor= MessageHeaderAccessor.getAccessor(message,StompHeaderAccessor.class);
//                 判断是不是链接，如果是，需要获取token，并且设置用户对象
                        if (StompCommand.CONNECT.equals(accessor.getCommand())){
                            String token = accessor.getFirstNativeHeader("Auth-Token");
                            if (!StringUtils.isEmpty(token)){
                                String authToken = token.substring(tokenHead.length());
                                String username = jwtTokenUtils.getUsernameFromToken(authToken);
//                                t
                                if (!StringUtils.isEmpty(username)){
//                                    登录
                                    UserDetails userDetails = myUserDetailService.loadUserByUsername(username);
//                                    验证用户是否有效，重新设置用户对象
                                    if (jwtTokenUtils.validateToken(authToken,userDetails)){
                                        UsernamePasswordAuthenticationToken authticationToken =
                                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                                        SecurityContextHolder.getContext().setAuthentication(authticationToken);
                                        accessor.setUser(authticationToken);
                                    }

                                }
                            }

                        }

                return message;
            }
        });

    }

    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
//        配置代理域，可以配置多个，配置代理目的地的前缀为/queue，可以在配置上向客户推送消息
         registry.enableSimpleBroker("/queue");

    }
}
